/**
 * title: 学生管理系统
 * Routes:
 *      - src/router/PrivateRouter
 */
import React, { Component } from 'react'
import { Form, Input, message, Spin, Button, Radio, Switch, Select } from "antd"
import { addStudent, updateStudent, getStudentBySNo } from "../../services/students"
import withRouter from "umi/withRouter"
import Avatar from "../Avatar"
// import Cascard from "../Cascard"
import Cascard from "../Cascard/cardCom"

message.config({
    top: 100,
    maxCount: 3,
});
const spanConfig = {
    labelCol: {
        span: 3
    },
    wrapperCol: {
        span: 12
    }
}
class StudentForm extends Component {
    state = {
        isLoading: false,
        disabled: this.props.sNo === undefined ? false : true
    }
    async componentDidMount() {
        if (this.props.sNo) {
            this.setState({
                isLoading: true
            })
            const stu = await getStudentBySNo(this.props.sNo)
            delete stu.id
            delete stu.appkey
            delete stu.ctime
            delete stu.utime
            this.props.form.setFields(getFieldsConfig(stu))
            this.setState({
                isLoading: false
            })
            stu.address = stu.address.split(",")
            console.log(stu);
        }
    }
    createOptions() {
        const options = []
        for (let i = 1980; i < 2010; i++) {
            options.push(<Select.Option key={i} value={i}>{i}</Select.Option>)
        }
        return options
    }
    async add(stuObj) {
        this.setState({
            isLoading: true
        })
        const resp = await addStudent(stuObj)
        if (resp.status === "success") {
            await message.success("添加成功!", 1)
            this.props.history.push("/student")
        } else {
            message.error(resp.msg, 3)
            this.setState({
                isLoading: false
            })
        }
    }
    async update(stuObj) {
        this.setState({
            isLoading: true
        })
        const resp = await updateStudent(stuObj)
        if (resp.status === "success") {
            await message.success("修改成功!", 1)
            this.props.history.push("/student")
        } else {
            message.error(resp.msg, 3)
            this.setState({
                isLoading: false
            })
        }
    }
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, value) => {
            if (!err) {
                // console.log(value);
                if (this.props.sNo) {
                    //修改学生
                    this.update(value)
                } else {
                    //添加学生
                    this.add(value)
                }
            }
        });

    }
    render() {
        const { getFieldDecorator } = this.props.form;

        return (
            <div>
                <Spin spinning={this.state.isLoading} tip="提交中，请稍后···">
                    <Form {...spanConfig} onSubmit={this.handleSubmit}>
                        <Form.Item label="头像">
                            {getFieldDecorator("avatar")(<Avatar />)}
                        </Form.Item>
                        <Form.Item label="学号">
                            {getFieldDecorator("sNo", {
                                rules: [
                                    {
                                        required: true,
                                        message: '学号必需填写',
                                    },
                                ]
                            })(<Input disabled={this.state.disabled} />)}
                        </Form.Item>
                        <Form.Item label="姓名">
                            {getFieldDecorator("name", {
                                rules: [
                                    { required: true, message: "姓名必须填写" }
                                ]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item label="性别">
                            {getFieldDecorator("sex", {
                                rules: [
                                    { required: true, message: "性别必须选择" }
                                ]
                            })(<Radio.Group>
                                <Radio.Button value={0}>男</Radio.Button>
                                <Radio.Button value={1}>女</Radio.Button>
                            </Radio.Group>)}
                        </Form.Item>
                        <Form.Item label="班长">
                            {getFieldDecorator("isMonitor", {
                                valuePropName: 'checked'
                            })(<Switch />)}
                        </Form.Item>
                        <Form.Item label="出生年份">
                            {getFieldDecorator("birth", {
                                rules: [
                                    { required: true, message: "出生年份必须填写" }
                                ]
                            })(<Select>
                                {this.createOptions()}
                            </Select>)}
                        </Form.Item>
                        <Form.Item label="手机号">
                            {getFieldDecorator("phone", {
                                rules: [
                                    { required: true, message: "手机号必须填写" },
                                    { pattern: /1\d{10}/, message: "手机格式不正确" }
                                ]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item label="地址">
                            {getFieldDecorator("address", {
                                initialValue: '123',
                                rules: [
                                    { required: true, message: "地址必须填写" }
                                ]
                            })(<Cascard />)}
                        </Form.Item>
                        <Form.Item label="邮箱">
                            {getFieldDecorator("email", {
                                rules: [
                                    { required: true, message: "邮箱必须填写" },
                                    { pattern: /\w+@\w+(\.\w+){1,2}/, message: "邮箱格式不正确" }
                                ]
                            })(<Input />)}
                        </Form.Item>
                        <Form.Item wrapperCol={{
                            offset: 3
                        }}>
                            <Button htmlType="submit" type="primary">提交</Button>
                        </Form.Item>
                    </Form>
                </Spin>
            </div>
        )
    }
}

function getFieldsConfig(obj) {
    const result = {}
    for (const prop in obj) {
        result[prop] = Form.createFormField({
            value: obj[prop]
        })
    }
    return result
}

const HOC = Form.create({
    //配置默认值
    mapPropsToFields: props => getFieldsConfig({
        sex: 0,
        isMonitor: false
    })
})

export default withRouter(HOC(StudentForm))

